package com.ljy.cart.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ljy.cart.Feign.FeignProductService;
import com.ljy.cart.interceptor.CartInterceptor;
import com.ljy.cart.service.CartService;
import com.ljy.cart.vo.Cart;
import com.ljy.cart.vo.CartItem;
import com.ljy.cart.vo.SkuInfoVo;
import com.ljy.cart.vo.UserInfoTo;
import com.ljy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private FeignProductService productService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "jymail:cart:";//购物车的前缀


    /*购物车添加数据功能*/
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        //在redis中查询是否有数据
        String res = (String) cartOps.get(skuId.toString());


        if (StringUtils.isEmpty(res)) {
            //购物车没有商品
            //2、新商品添加到购物车
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加的商品的信息
                R skuInfo = productService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {});
                cartItem.setCheck(true);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setCount(num);
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            },executor);
            //2、远程查询商品详细信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            },executor);
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();

            //3、将数据保存到redis,key-商品Id,value-
            //为了存储到redis后可以识别，需要将对象转换为字符串类型
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);
            return cartItem;
        }
        else {
            //购物车有此商品,修改数量即可
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);

            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;

        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps =
                getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {


        Cart cart = new Cart();
        //1、登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            //1、登录
            String cartKey = CART_PREFIX+userInfoTo.getUserId();
            String temptCartKey = CART_PREFIX+userInfoTo.getUserKey();
            //2、如果临时购物车的数据没有合并
            List<CartItem> tempCart = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if (tempCart!=null){
                //说明购物车有数据需要合并
                for (CartItem item:tempCart){
                    addToCart(item.getSkuId(),item.getCount());
                }
                //清除临时购物车数据
                clearCart(temptCartKey);
            }
            //获取登陆后的购物车的数据,包含登陆后的数据与临时购物车的数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);


        }else {
            //没登陆
            String userKey =CART_PREFIX+userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setItems(cartItems);
        }

        return cart;
    }

    /*
     * 清除临时购物车数据
     * */
    @Override
    public void clearCart(String cartKey) {
        //清除所有
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),jsonString);
    }



    @Override
    public void countItem(Long skuId, String countNum) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(Integer.parseInt(countNum));
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String jsonString = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),jsonString);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()==null){
            return null;
        }else {
            String cartKey = CART_PREFIX+userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            //获取所有选中的购物项
            List<CartItem> collect = cartItems.stream().filter(item -> item.getCheck()).map(item->{
                R price = productService.getPrice(item.getSkuId());
                //TODO 更新为最新价格
                String data = (String) price.get("data");
                item.setPrice(new BigDecimal(data));
                return item;
            }).collect(Collectors.toList());
            return collect;
        }


    }


    /*
    * 获取到我们要操作的购物车
    *
    * */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1、得到用户信息,判断用户是否登录，信息添加到临时还是本地购物车
        String cartKey="";//redis前缀名
        if (userInfoTo.getUserId()!=null){
         //用户登录了
            cartKey=CART_PREFIX+userInfoTo.getUserId();
        }else {
            //用户没有登录
            cartKey=CART_PREFIX+userInfoTo.getUserKey();
        }

        //判断当前redis是否有商品
        //绑定hash操作,之后所有的操作都是针对这个key
        BoundHashOperations<String, Object, Object> hashOperations = stringRedisTemplate.boundHashOps(cartKey);
        return hashOperations;
    }


    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values!=null && values.size() > 0){
            List<CartItem> collect = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }

        return null;
    }


}
